package org.jjche.file.conf;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import org.dromara.x.file.storage.spring.SpringFileStorageProperties;
import org.jjche.core.constant.FileConstant;
import org.jjche.security.config.AuthorizeRequestsCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 文件权限配置
 * </p>
 *
 * @author miaoyj
 * @since 2024-03-30
 */
@Configuration("fileSecurityConfiguration")
public class FileSecurityConfiguration {
    @Resource
    private SpringFileStorageProperties fileStorageProperties;

    @Bean("fileAuthorizeRequestsCustomizer")
    public AuthorizeRequestsCustomizer authorizeRequestsCustomizer() {
        List<? extends SpringFileStorageProperties.SpringLocalPlusConfig> localPlusConfigs = fileStorageProperties.getLocalPlus();
        SpringFileStorageProperties.SpringLocalPlusConfig localPlusConfig = CollUtil.getFirst(localPlusConfigs);
        String pathPattern = null;
        if (localPlusConfig != null) {
            String[] pathPatterns = localPlusConfig.getPathPatterns();
             pathPattern = ArrayUtil.get(pathPatterns, 0);
        }
        String finalPathPattern = pathPattern;
        FileConstant.FILE_PATH_MATCH = pathPattern;
        return new AuthorizeRequestsCustomizer() {

            @Override
            public void customize(ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry) {
                // 访问头像和文件不限制权限
                registry.antMatchers(finalPathPattern).permitAll();
            }
        };
    }
}
